//
//  MessageViewController.m
//  sklive
//
//  Created by Macx on 2017/7/7.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MessageViewController.h"
#import "PerMessageViewController.h"
#import "MessageTableViewCell.h"
#import "TCMsgHandler.h"
#import "SystemMessageViewController.h"
#import "privateChat.h"

#import "UIViewController+KNSemiModal.h"

@interface MessageViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *arr;

// 私聊
@property (nonatomic, strong) NSMutableArray *conversationArr;
@property (nonatomic, strong) NSMutableArray *chatListArr; // 列表数组


@property (nonatomic, strong) NSString *num0;
@property (nonatomic, strong) NSString *num1;

@property (nonatomic, strong) UIView *redV;

@property (nonatomic, strong) NSMutableArray *indexArr;

@end

@implementation MessageViewController

- (void)viewWillLayoutSubviews {
    
    if (self.isLive) {
        self.view.frame = CGRectMake(0, SCREEN_HEIGHT/2, SCREEN_WIDTH, SCREEN_HEIGHT/2);
    }
}


- (void)viewWillAppear:(BOOL)animated {
    
    [[NetworkTool sharedTool] requestWithName:@"未读消息" URLString:APIUnreadTips parameters:nil method:@"GET" callBack:^(id responseObject) {
        
        self.num0 = responseObject[@"data"][@"notification"];
        self.num1 = responseObject[@"data"][@"message"];
        
//        [self.tableView reloadData];
        
    }];
    
    [self chatListConversations];
    
    if (self.isLive) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (void)c2cNotification:(NSNotification *)notification {
    NSLog(@"--接收到私聊提醒通知--\n%@", notification.userInfo);
//    [self updateNum];
    [self chatListConversations];
    
}

- (void)msgchatVC:(NSNotification *)notification {
    NSDictionary *privateChat = notification.userInfo;
    NSLog(@"--接收到私聊的消息通知--\n%@", privateChat);
    
    NSString *str = privateChat[@"receiveInfo"]; // 把聊天对象信息赋值
    
    NSError *err;
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
    
    
    TIMConversation *conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:infoDict[@"imId"]];
    
    [conversation setReadMessage];
    
    //    NSMutableArray *chatArr = self.chatListArr[tag];
    //
    //    NSDictionary *dict = chatArr[1];
    IMAUser *user = [[IMAUser alloc] init];
    user.nickName = infoDict[@"nickname"];
    user.userId = infoDict[@"uid"];
    user.remark = infoDict[@"nickname"];
    user.icon = infoDict[@"headpic"];
    
#if kTestChatAttachment
    // 无则重新创建
    ChatViewController *chatVC= [[CustomChatUIViewController alloc] initWith:user];
#else
    ChatViewController *chatVC = [[IMAChatViewController alloc] initWith:user];
#endif
    
    chatVC.isLive = self.isLive;
    
    [self.navigationController pushViewController:chatVC animated:YES];
    
    
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"c2cNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"msgchatVC" object:nil];
//    self.tableView.dataSource = nil;
//    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(c2cNotification:)name:@"c2cNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(msgchatVC:)name:@"msgchatVC" object:nil];
    
    self.indexArr = [[NSMutableArray alloc] init];
    
    self.arr = @[@"系统消息", @"私聊"];
    if (self.isLive) {
        self.arr = @[@"私聊"];
    }
    
    [self buildUI];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.navigationItem.title = @"消息";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    
    if (self.isLive) {
        
//        UIView *headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
//        [self.view addSubview:headBgView];
//        headBgView.backgroundColor = kWhiteColor;
        
        UILabel *chatHead = [[UILabel alloc] init];
        [self.view addSubview:chatHead];
        chatHead.font = kUHSystemFontWithSize(14);
        chatHead.textColor = kBlackColor;
        chatHead.backgroundColor = kWhiteColor;
        chatHead.layer.borderColor = UISeparatedColorRGB.CGColor;
        chatHead.text = [NSString stringWithFormat:@"私信"];
        chatHead.textAlignment = NSTextAlignmentCenter;
        chatHead.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
        
        UIButton *closeChat = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:closeChat];
        [closeChat setImage:[UIImage imageNamed:@"live_zhubo_close"] forState:UIControlStateNormal];
        closeChat.frame = CGRectMake(SCREEN_WIDTH-40, 0, 40, 40);
        [closeChat addTarget:self action:@selector(maskClick) forControlEvents:UIControlEventTouchUpInside];
        
        self.tableView.frame = CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT/2-40);
    }
    
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.sectionHeaderHeight = 30;
//    self.tableView.scrollEnabled = NO;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    
}

- (void)maskClick {
    
//    self.navigationController.view.hidden = YES;
    
//    self.view.hidden = YES;
    
//    [self.navigationController.view removeFromSuperview];
    self.navigationController.view.hidden = YES;
    
//    UIViewController * parent = [self.view containingViewController];
//    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
//        [parent dismissSemiModalView];
//    }
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.isLive) {
        MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.num.hidden = YES;
        NSArray *arr = self.chatListArr[indexPath.row];
        NSDictionary *dict = arr[1];
        cell.nickName.text = dict[@"nickname"];
        [cell.headPic sd_setImageWithURL:[NSURL URLWithString:dict[@"face"]] placeholderImage:IMAGE(@"placeHolder")];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.sign.hidden = NO;
        CGSize nickNameSize = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)];
        cell.nickName.frame = CGRectMake(20+SW(9), cell.headPic.centerY-nickNameSize.height-2, SW(2), nickNameSize.height);
        cell.sign.text = arr[0];
        if (![arr[2] isEqualToString:@"0"]) {
            cell.num.text = arr[2];
            cell.num.hidden = NO;
        }
        else
            cell.num.hidden = YES;
        cell.date.hidden = YES;
        
        // 点击过就隐藏
        for (int i = 0; i < self.indexArr.count; i++) {
            if ([self.indexArr[i] isEqualToString:[NSString stringWithFormat:@"%ld", indexPath.row]]) {
                cell.num.hidden = YES;
            }
        }
        
        cell.contentView.tag = indexPath.row;
        [cell.contentView addTarget:self action:@selector(tableViewCellClick:)];
        
        return cell;
    }
    
    if (indexPath.section == 0) {
        
        MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.sign.hidden = YES;
        cell.date.hidden = YES;
        cell.num.hidden = YES;
        cell.num.x = SCREEN_WIDTH-SW(20)-30;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.nickName.centerY = cell.headPic.centerY;
        NSLog(@"---num-%@, %@", self.num0, self.num1);
        if (indexPath.row == 0) {
            cell.headPic.image = IMAGE(@"icon_info_system");
            cell.nickName.text = @"系统消息";
            if (![self.num0 isEqualToString:@"0"] && self.num0) {
                cell.num.text = self.num0;
                cell.num.hidden = NO;
            }
        }
        else {
            cell.headPic.image = IMAGE(@"icon_info_question");
            cell.nickName.text = @"站内信";
            if (![self.num1 isEqualToString:@"0"] && self.num1) {
                cell.num.text = self.num1;
                cell.num.hidden = NO;
            }
        }
        return cell;
    }
    
    else {
        MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.num.hidden = YES;
        NSArray *arr = self.chatListArr[indexPath.row];
        NSDictionary *dict = arr[1];
        cell.nickName.text = dict[@"nickname"];
        [cell.headPic sd_setImageWithURL:[NSURL URLWithString:dict[@"face"]] placeholderImage:IMAGE(@"placeHolder")];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.sign.hidden = NO;
        CGSize nickNameSize = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)];
        cell.nickName.frame = CGRectMake(20+SW(9), cell.headPic.centerY-nickNameSize.height-2, SW(2), nickNameSize.height);
        cell.sign.text = arr[0];
        if (![arr[2] isEqualToString:@"0"]) {
            cell.num.text = arr[2];
            cell.num.hidden = NO;
        }else {
            // 如果为0，则说明信息都已经读过了
            cell.num.hidden = YES;
        }
        cell.date.hidden = YES;

        
        // 点击过就隐藏
        for (int i = 0; i < self.indexArr.count; i++) {
            if ([self.indexArr[i] isEqualToString:[NSString stringWithFormat:@"%ld", indexPath.row]]) {
                cell.num.hidden = YES;
            }
        }
        
        return cell;
        
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isLive) {
        return self.chatListArr.count;
    }
    if (section == 0) {
        return 2;
    }
    else
        return self.chatListArr.count;
}- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SW(9)+20;
}
//    设置分区高度 也可以使用代理方法
//_tableView.sectionHeaderHeight = 30;
//   tableView代理方法 设置分区高度（可以根据不同分区设置不同高度等实现自定义）
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
//  自定义分区头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString * identy = @"head";
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    if (!hf) {
        NSLog(@"%ld",(long)section);
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
//        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 30)];
//        [hf addSubview:title];
//        title.text = self.arr[section];
        
//        title.font = kUHSystemFontWithSize(15);
    }
    return hf;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    if (self.isLive) {
        
        TIMConversation *conversation = self.conversationArr[indexPath.row];
        
        [conversation setReadMessage];
        
        NSMutableArray *chatArr = self.chatListArr[indexPath.row];
        
        NSDictionary *dict = chatArr[1];
        IMAUser *user = [[IMAUser alloc] init];
        user.nickName = dict[@"nickname"];
        user.userId = dict[@"user_id"];
        user.remark = dict[@"nickname"];
        user.icon = dict[@"face"];
        
#if kTestChatAttachment
        // 无则重新创建
        ChatViewController *chatVC= [[CustomChatUIViewController alloc] initWith:user];
#else
        ChatViewController *chatVC = [[IMAChatViewController alloc] initWith:user];
#endif
        
        chatVC.isLive = self.isLive;
        
        [self.indexArr addObject:[NSString stringWithFormat:@"%ld", indexPath.row]];
        
        [self.navigationController pushViewController:chatVC animated:YES];
        return;
    }
    
//    Message *model = self.infoArr[indexPath.row];
//    
//    PerMessageDetailsViewController *detailVC = [[PerMessageDetailsViewController alloc] init];
//    detailVC.mId = [NSString stringWithFormat:@"%@", [model valueForKey:@"mId"]];
//    [self.navigationController pushViewController:detailVC animated:YES];
    if (indexPath.section == 0 && indexPath.row == 0) {
        [self.navigationController pushViewController:[[SystemMessageViewController alloc] init] animated:YES];
    }
    
    else if (indexPath.section == 0 && indexPath.row == 1) {
        [self.navigationController pushViewController:[[PerMessageViewController alloc] init] animated:YES];
    }
    else {
        /**
         *   点击消息列表，这里进入一个聊天消息详情的界面。
         */
//        if (_chatVC == nil) {
//            _chatVC = [[ XYDJViewController  alloc] init];
//        }
//        /**
//         下面的这个 TLUser 就是具体到用户的一个数据 model
//         */
//        ZXUser *user7 = [[ZXUser alloc] init];
//        user7.username = @"文小雨";
//        user7.userID = @"XB";
//        user7.nikename = @"小贝";
//        user7.avatarURL = @"10.jpeg";
//        _chatVC.user = user7;
        
         TIMConversation *conversation = self.conversationArr[indexPath.row];
//        NSArray *arr = self.chatListArr[indexPath.row];
//        NSDictionary *dict = arr[1];
        
        [conversation setReadMessage];
        
        /*
        XZGroup *group = [[XZGroup alloc] init];
        group.gName = dict[@"nickname"];
        XZChatViewController *chatVC = [[XZChatViewController alloc] init];
        chatVC.group = group;
        chatVC.currConversation = conversation;
        
        
        
        NSDictionary *userInfo = GetUserDefaule(USERINFO);
        NSDictionary *infoDict = @{@"imId":[userInfo valueForKey:@"user_id"],
                                   @"uid":[userInfo valueForKey:@"user_id"],
                                   @"nickname":userInfo[@"nickname"],
                                   @"headpic":userInfo[@"face"],
                                   @"level":[NSString stringWithFormat:@"%@", [userInfo valueForKey:@"level"]]};
        
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
        NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        chatVC.senderInfo = infoStr;
        
        NSDictionary *infoDict2 = @{@"imId":dict[@"user_id"],
                                    @"uid":dict[@"user_id"],
                                    @"nickname":dict[@"nickname"],
                                    @"headpic":dict[@"face"],
                                    @"level":[NSString stringWithFormat:@"%@", [dict valueForKey:@"level"]]};
        
        NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:infoDict2 options:NSJSONWritingPrettyPrinted error:&parseError];
        NSString *infoStr2 = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
        chatVC.receiveInfo = infoStr2;
        */
        
        NSMutableArray *chatArr = self.chatListArr[indexPath.row];
//        TIMUserProfile *profile = chatArr[1];
        //        chatArr[2] = @"0";
//        IMAUser *user = [[IMAUser alloc] init];
//        user.nickName = profile.nickname;
//        user.userId = profile.identifier;
//        user.remark = profile.nickname;
//        user.icon = profile.faceURL;
        
        NSDictionary *dict = chatArr[1];
        IMAUser *user = [[IMAUser alloc] init];
        user.nickName = dict[@"nickname"];
        user.userId = dict[@"user_id"];
        user.remark = dict[@"nickname"];
        user.icon = dict[@"face"];
        
        
        #if kTestChatAttachment
            // 无则重新创建
            ChatViewController *chatVC = [[CustomChatUIViewController alloc] initWith:user];
        #else
        ChatViewController *chatVC = [[IMAChatViewController alloc] initWith:user];
        #endif
        
        [self.indexArr addObject:[NSString stringWithFormat:@"%ld", indexPath.row]];
        
        // 隐藏底部的buttomBar 当 push 的时候
//        [self setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:chatVC animated:YES];
        
    }
}


- (void)tableViewCellClick:(UITableViewCell *)sender {
    
    
    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer
                                             *)sender;
    
    NSInteger tag = [tapRecognizer.view tag];
    
    TIMConversation *conversation = self.conversationArr[tag];
    
    [conversation setReadMessage];
    
    NSMutableArray *chatArr = self.chatListArr[tag];
    
    NSDictionary *dict = chatArr[1];
    IMAUser *user = [[IMAUser alloc] init];
    user.nickName = dict[@"nickname"];
    user.userId = dict[@"user_id"];
    user.remark = dict[@"nickname"];
    user.icon = dict[@"face"];
    
#if kTestChatAttachment
    // 无则重新创建
    ChatViewController *chatVC= [[CustomChatUIViewController alloc] initWith:user];
#else
    ChatViewController *chatVC = [[IMAChatViewController alloc] initWith:user];
#endif
    
    chatVC.isLive = self.isLive;
    
    [self.indexArr addObject:[NSString stringWithFormat:@"%ld", tag]];
    
    [self.navigationController pushViewController:chatVC animated:YES];
}


#pragma mark ===========私聊列表=========

- (void)chatListConversations {
    [_tableView reloadData];
    [privateChat chatListConversationBlock:^(NSMutableArray *conversationArr, NSMutableArray *chatListArr) {
        
        NSMutableArray *userArr = [[NSMutableArray alloc] init];
        for (NSArray *arr in chatListArr) {// 信息 userId 未读数量
            NSString *uid = arr[1];
            [userArr addObject:uid];
        }
        
//        NSLog(@"userArr = %@", userArr);
        
        NSString *userIdStr = [userArr componentsJoinedByString:@","];
        // 批量查询用户信息
        NSDictionary *param = @{@"ids":userIdStr,
                                @"per_page":@"10000"};
        [[NetworkTool sharedTool] requestWithName:@"批量查询用户信息" URLString:APIUserInfos parameters:param method:@"GET" callBack:^(id responseObject) {
            
            NSArray *arr = [[NSArray alloc] init];
            arr = responseObject[@"data"];
            
            NSMutableDictionary *userDict = [[NSMutableDictionary alloc] init];
            
            for (int i = 0; i < arr.count; i++) {
                NSDictionary *user = [[NSDictionary alloc] init];
                user = arr[i];
                [userDict setValue:user forKey:user[@"user_id"]];
            }
            
//            NSLog(@"1111 %@", chatListArr);
            for (NSMutableArray *ma in chatListArr) {
                NSString *uid = ma[1];
                [ma removeObjectAtIndex:1];
                [ma insertObject:userDict[uid] atIndex:1];
            }
//            NSLog(@"user %@", chatListArr);
         
            
            [self.chatListArr removeAllObjects];
            [self.conversationArr removeAllObjects];
            [self.chatListArr setArray:chatListArr];
            [self.conversationArr setArray:conversationArr];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            
        }];
    }];
}

// 懒加载
- (NSMutableArray *)conversationArr {
    if (_conversationArr == nil) {
        _conversationArr = [[NSMutableArray alloc] init];
    }
    return _conversationArr;
}
- (NSMutableArray *)chatListArr {
    if (_chatListArr == nil) {
        _chatListArr = [[NSMutableArray alloc] init];
    }
    return _chatListArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
